package com.gee.spring.boot.influxdb.config;

import com.gee.spring.boot.influxdb.core.InfluxdbTemplate;
import com.gee.spring.boot.influxdb.core.convertor.BytesHexConvertor;
import com.gee.spring.boot.influxdb.core.convertor.LocalDateTimeNanosConvertor;
import com.gee.spring.boot.influxdb.core.util.AppContextUtil;
import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.concurrent.TimeUnit;

/**
 * @author gepengjun
 * @since 2024/4/24 13:44
 */
@Configuration
@EnableConfigurationProperties(InfluxdbProperties.class)
@ConditionalOnProperty(prefix = "spring.influxdb", value = "enable", matchIfMissing = true)
@Import({AppContextUtil.class, BytesHexConvertor.class, LocalDateTimeNanosConvertor.class})
public class InfluxdbAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public InfluxDB influxdb(InfluxdbProperties influxdbProperties) {
        OkHttpClient.Builder client = new OkHttpClient.Builder().readTimeout(influxdbProperties.getReadTimeout(), TimeUnit.SECONDS);
        InfluxDB influxDB = InfluxDBFactory.connect(influxdbProperties.getUrl(), influxdbProperties.getUser(), influxdbProperties.getPassword(), client);
        influxDB.setDatabase(influxdbProperties.getDatabase());
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }

    @Bean
    public InfluxdbTemplate influxdbTemplate(InfluxdbProperties influxdbProperties) {
        return new InfluxdbTemplate(influxdbProperties.getDatabase());
    }
}
